package com.chl.xadmin.sys.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chl.xadmin.common.vo.Result;
import com.chl.xadmin.sys.entity.Role;
import com.chl.xadmin.sys.service.IRoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author chl
 * @since 2023-09-29
 */
@Api(tags = "角色管理")
@RestController
@RequestMapping("/sys/role")
public class RoleController {
    @Autowired
    private IRoleService roleService;

    @ApiOperation("分页获取角色信息")
    @GetMapping("/list")
    public Result<?> getRoleListPage(@RequestParam(value = "roleName", required = false) String roleName,
                                     @RequestParam(value = "pageNumber") Long pageNumber,
                                     @RequestParam(value = "pageSize") Long pageSize) {
        LambdaQueryWrapper<Role> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StringUtils.hasLength(roleName), Role::getRoleName, roleName);

        Page<Role> page = new Page<>(pageNumber, pageSize);
        roleService.page(page, wrapper);

        Map<String, Object> data = new HashMap<>();
        data.put("total", page.getTotal());
        data.put("rows", page.getRecords());
        return Result.success(data);
    }

    @ApiOperation("添加角色")
    @PostMapping
    public Result<?> addRole(@RequestBody Role role) {
        roleService.addRole(role);
        return Result.success("添加角色成功");
    }

    @ApiOperation("修改角色信息")
    @PutMapping
    public Result<?> updateRole(@RequestBody Role role) {
        roleService.updateRole(role);
        return Result.success("修改角色成功");
    }

    @ApiOperation("根据id获取角色信息")
    @GetMapping("/{id}")
    public Result<Role> getRoleById(@PathVariable("id") Integer id) {
        Role role = roleService.getRoleById(id);
        return Result.success(role);
    }

    @ApiOperation("删除角色")
    @DeleteMapping("/{id}")
    public Result<Role> deleteRoleById(@PathVariable("id") Integer id) {
        roleService.deleteRoleById(id);
        return Result.success("删除角色成功");
    }

    @ApiOperation("获取所有角色")
    @GetMapping("/all")
    public Result<List<Role>> getAllRole() {
        List<Role> roleList = roleService.list();
        return Result.success(roleList);
    }

    @ApiOperation("上传头像")
    @PostMapping("/upload")
    public Object upload(MultipartFile file, HttpServletRequest request){
        // 获取项目相对路径
        String path = System.getProperty("user.dir");
        // 生成图片存储目录
        File imagePath = new File(path+"/src//main/resources/static/images");
        // 时间格式化
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        // 时间目录
        String directory = simpleDateFormat.format(new Date());
        File imageResultPath = new File(imagePath + "\\" + directory);
        // 判断目录是否存在，不存在则创建
        if(!imageResultPath.exists()){
            imageResultPath.mkdirs();
        }
        // 后缀
        String suffix = Objects.requireNonNull(file.getOriginalFilename()).substring(file.getOriginalFilename().lastIndexOf("."));
        // 新文件名
        String newFileName= UUID.randomUUID().toString().replaceAll("-", "")+suffix;
        System.out.println("图片路径：" + imageResultPath);
        System.out.println("图片名：" + newFileName);
        System.out.println("存储路径："+imageResultPath + "\\" + newFileName);
        // 创建新文件
        File newFile = new File(imageResultPath + "\\" + newFileName);


        try {
            file.transferTo(newFile);
            //协议 :// ip地址 ：端口号 / 文件目录(/images/2020/03/15/xxx.jpg)
            String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/images/" + directory + "/" + newFileName;
            System.out.println("图片上传，访问URL：" + url);
            Map<String, Object> data = new HashMap<>();
            data.put("avatar", url);
            return Result.success(data);
        } catch (IOException e) {
            return Result.error("角色头像上传失败");
        }
    }
}
